import store from '../store'

/*
	*.vue使用示例
		1.链接
			this.$ws.init(uid) 
	 
		2.发送 msg消息格式JSON
			let msg = {
				ontent:'你好',
				type:'text/img'
				...
			}
			this.$ws.send(msg)
	 
		3.主动关闭链接
			this.$ws.close()
 */

const webSocketUrl = 'ws://10.1.100.248:8080/api/v2/websocket/87'
let pingPong = 'ping'

// 创建连接
const init = (uid) => {
	//返回一个promise实例。  
	return new Promise((resolve, reject) => {  
		console.log("isOpenWebSocket--11--"+store.state.isOpenWebSocket)
		uni.connectSocket({
			url: webSocketUrl + uid ,
			// url: webSocketUrl,
			success: (res) => {
				uni.onSocketOpen(function (res) {
					console.log('WebSocket连接已打开！');
					store.state.isOpenWebSocket = true
					console.log("---isOpenWebSocket--"+store.state.isOpenWebSocket)
					
					heartCheck()
					receive()
					listeningClose()
					
					resolve(res)
				});
			},
			fail: (err) => {
				console.log("webSocket连接失败")
				reject(err) 
			},
			complete:(com) => {
				console.log("com",com)
			}
		});
		
		
	})  
}

// 发送消息
const send = (message) => {
	uni.sendSocketMessage({
		data: message
	});
}

// 接收消息
const receive = () => {
	uni.onSocketMessage((res) => {
		console.log('收到服务器内容：res',res);
		
		store.commit('saveWebScoket',res.data)
		
		let jsonData = JSON.parse(res.data)
		if(jsonData.hash_id){
			const innerAudioContext = uni.createInnerAudioContext();
			innerAudioContext.autoplay = true;
			innerAudioContext.src = 'https://img.tukuppt.com/newpreview_music/08/99/00/5c88d4ac45bb536047.mp3';
			innerAudioContext.onPlay(() => {
			  console.log('开始播放提示音');
			});
			innerAudioContext.destroy
		}
		
		let json = JSON.parse(res.data)
		// 控制消息点点显示
		if(json.body != undefined && json.body != "" && json.type==="system"){
			store.commit('setMsgFlag',true)
		}
		
		if (res.data === 'pong') {
			pingPong = 'pong'
		}
	});
}


// 主动关闭连接
const close = (msg) => {
	uni.closeSocket();
	store.state.isOpenWebSocket = false
	
	console.log('主动关闭 websocket');
	console.log("---isOpenWebSocket--"+store.state.isOpenWebSocket)
}

// 监听WebSocket关闭
const listeningClose = () => {
	uni.onSocketClose((res) => {
		store.state.isOpenWebSocket = false
		console.log("onSocketClose--",res)
		console.log('监听到WebSocket 已关闭！');
		
		console.log("开始重连")
		let initTimeOut = setTimeout(() => {
			console.log('重新连接 初始化',new Date());
			initTimeOut = null
			init(store.state.userInfo.uid)
		}, 2000)
	});
}

// 心跳
const heartCheck = () => {

	const timer = 1000 * 60
	
	let pingInterval = setInterval(() => {
		console.log("this.pingPong---ppppppp-"+pingPong)
		// 判断连接是否打开
		if (store.state.isOpenWebSocket) {
			console.log('ping',new Date());
			send('ping')
		}
	},timer)
	
	let pongInterval = setInterval(() => {
		console.log("this.pingPong--aaaaaaaaaaaa--"+pingPong)
		if (pingPong === 'ping--') {
			console.log('pong未返回,准备关闭',new Date());
			clearInterval(pingInterval)
			clearInterval(pongInterval)
	
			close()
			relink()
		} else {
			// console.log('pong',new Date());
			pingPong = 'ping'
		}
	}, timer)
	
	
	// 重连
	const relink = () => {
		console.log('开始重新连接');
		let initTimeOut = null
		if (store.state.isOpenWebSocket) {
			// 连接正常
			console.log('状态正常,无需重新连接',new Date());
			return
		}
		if (initTimeOut) {
			// 定时器已经启动
			console.log('正在重连,定时器已启动,退出',new Date());
			return
		}
		initTimeOut = setTimeout(() => {
			console.log('重新连接 初始化',new Date());
			clearInterval(pingInterval)
			clearInterval(pongInterval)
			initTimeOut = null
			init(store.state.userInfo.uid)
		}, 2000)
	}
	
}



module.exports = {init,send,receive,close}
		